package com.ldl.origami.controller.entity;

import com.ldl.origami.common.ErrorModelAndView;
import com.ldl.origami.domain.News;
import com.ldl.origami.domain.User;
import com.ldl.origami.origamiService.UserService;
import com.ldl.origami.util.Constants;
import com.ldl.origami.util.InitServlet;
import com.ldl.origami.util.OrigamiUtils;
import com.ldl.origami.util.ScaleImageUtils;
import com.ldl.origami.websocket.SystemWebSocketHandler;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 功能描述:涉及到用户相关操作的Controller
 * 作者: LDL
 * 创建时间: 2014/8/20 15:07
 */
@Controller
public class UserController{

    static org.slf4j.Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;

    @Bean
    public SystemWebSocketHandler systemWebSocketHandler() {
        return new SystemWebSocketHandler();
    }

    /**
     * 全部消息
     * @param request
     * @return
     */
    @RequestMapping("/notification")
    public ModelAndView viewNews(HttpServletRequest request){
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);
        User user = null;
        List<News> newses = null;
        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
                newses =  userService.getNewsByUserName(userName);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.addObject("newses", newses);
        modelAndView.setViewName("news/viewNews");
        return modelAndView;
    }

    /**
     * 显示消息内容
     * @return
     */
    @RequestMapping("/newsContent")
    public ModelAndView newsContent(@RequestParam("newsID") int newsId,HttpServletRequest request){
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);
        userService.updateNewsById(newsId);
        News news = userService.getNewsById(newsId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("news",news);
        modelAndView.setViewName("/news/newsContent");

        List<News> newses = null;
        try {
            newses = userService.getNewsByUserName(userName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        systemWebSocketHandler().sendMessageToUser(userName, new TextMessage(newses.size() + ""));
        return modelAndView;
    }


    /**
     * 用户中心账号
     * @param request
     * @return
     */
    @RequestMapping("/account")
    public ModelAndView account(HttpServletRequest request){
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);

        User user = null;
        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("userCenter/account");
        return modelAndView;
    }

    /**
     * 更新账号信息
     * @param request
     * @return
     */
    @RequestMapping("/updateAccount")
    @ResponseBody
    public String updateAccount(HttpServletRequest request,HttpServletResponse response){
        String result = "success";
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);
        String newName = request.getParameter("newName");
        String email = request.getParameter("email");
        User user = new User();

        user.setUserName(newName);
        user.setUserMail(email);
        try {
            userService.updateUserAccount(user,userName);
        } catch (Exception e) {
            return  "error";
        }
        request.getSession().setAttribute(Constants.SESSION_USERNAME,newName);
        Cookie cookie = new Cookie("userName", newName);
        cookie.setMaxAge(InitServlet.cookieTime);
        cookie.setPath("/");
        response.addCookie(cookie);
        return result;
    }


    /**
     * 用户中心密码
     *
     * @param request
     * @return
     */
    @RequestMapping("/passwd")
    public ModelAndView passwd(HttpServletRequest request) {
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);

        User user = null;
        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("userCenter/passwd");
        return modelAndView;
    }

    /**
     * 用户中心资料
     *
     * @param request
     * @return
     */
    @RequestMapping("/info")
    public ModelAndView info(HttpServletRequest request) {
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);

        User user = null;
        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("userCenter/info");
        return modelAndView;
    }


    /**
     * 检验旧密码
     * @param request
     * @return
     */
    @RequestMapping("/checkOldPasswd")
    @ResponseBody
    public String checkOldPasswd(HttpServletRequest request){
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);
        String result = "no";
        String oldPasswd = request.getParameter("oldPasswd");
        User user = new User();
        user.setUserName(userName);
        user.setUserPasswd(DigestUtils.md5Hex(oldPasswd));
        List<User> users = null;
        try {
            users = userService.checkOldPasswd(user);
        } catch (Exception e) {
            return "error";
        }
        if(users!=null && users.size()>0){
            result = "success";
        }

        return result;
    }

    @RequestMapping("/changPasswd")
    @ResponseBody
    public String changPasswd(HttpServletRequest request){
        String result = "success";
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);
        String newPasswd = request.getParameter("newPasswd");
        User user = new User();
        user.setUserName(userName);
        user.setUserPasswd(DigestUtils.md5Hex(newPasswd));

        try {
            userService.updateUserPasswd(user);
        } catch (Exception e) {
            return "error";
        }

        return result;
    }



    /**
     * 头像上传保存
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/uploadHeadImage")
    @ResponseBody
    public String uploadTitleImage(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String path = request.getSession().getServletContext().getRealPath("/upload");
        String result = "";

        // 获得文件：
        MultipartFile multipartFile = multipartRequest.getFile("uploadfile");

        DateTime dateTime = new DateTime();
        String str = dateTime.toString("yyyymmddhhmmssSSSS");
        // 获得文件名：
        String fileFullName = multipartFile.getOriginalFilename();
        String fileType = fileFullName.substring(fileFullName.lastIndexOf("."), fileFullName.length());
        String fileName = fileFullName.substring(0, fileFullName.lastIndexOf(".")) + str + fileType;
        String savePath = "/imagetemp/" + fileName;
        String filePath = path + savePath;

        result = request.getContextPath() + "/upload" + savePath;
        try {
            ScaleImageUtils.resize(400, 400, filePath, multipartFile.getInputStream());
        } catch (IOException e) {
            result = "上传失败" + e.getMessage();
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 生成略缩图
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/thumbnailHeadImage")
    @ResponseBody
    public String uploadthumbnailimage(HttpServletRequest request, HttpServletResponse response) {
        int x = Integer.parseInt(request.getParameter("x1"));
        int y = Integer.parseInt(request.getParameter("y1"));
        int h = Integer.parseInt(request.getParameter("h"));
        int w = Integer.parseInt(request.getParameter("w"));
        String oldpath = request.getParameter("oldpath").replace(request.getContextPath(), "");
        String path = request.getSession().getServletContext().getRealPath(oldpath);
        String fileName = oldpath.substring(oldpath.lastIndexOf("/") + 1, oldpath.length());
        String dirImageFileUrl = request.getSession().getServletContext().getRealPath("/upload") + "/head/head_" + fileName;
        String showUrl = request.getContextPath() + "/upload/head/head_" + fileName;
        // 读取源图像
        try {
            Image img;
            ImageFilter cropFilter;
            BufferedImage bi = ImageIO.read(new File(path));
            int srcWidth = bi.getWidth(); // 源图宽度
            int srcHeight = bi.getHeight(); // 源图高度
            if (srcWidth >= w && srcHeight >= h) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight,
                        Image.SCALE_DEFAULT);
                cropFilter = new CropImageFilter(x, y, w, h);
                img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(), cropFilter));
                BufferedImage tag = new BufferedImage(w, h,
                        BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, null); // 绘制缩小后的图
                g.dispose();

                File dirImageFile = new File(dirImageFileUrl);
                if (!dirImageFile.exists()) {
                    dirImageFile.mkdirs();
                }
                // 输出为文件
                ImageIO.write(tag, "JPEG", dirImageFile);
            }
            File file = new File(path);
            file.delete();
        } catch (IOException e) {
            logger.debug("修改头像出错: " + OrigamiUtils.getErrorInfoFromException(e));
            return  "error";
        }


        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);
        User user = new User();
        user.setUserName(userName);
        user.setHeadimage(showUrl);

        try {
            userService.updateUserHeadImage(user);
        } catch (Exception e) {
            return "error";
        }
        return "success";
    }

    /**
     * 修改个人简介
     * @param request
     * @return
     */
    @RequestMapping("/updateProfile")
    @ResponseBody
    public String updateProfile(HttpServletRequest request){

        String profile = request.getParameter("profile");
        String userName = (String) request.getSession().getAttribute(Constants.SESSION_USERNAME);
        User user = new User();
        user.setUserName(userName);
        user.setProfile(profile);

        try {
            userService.updateUserProfile(user);
        } catch (Exception e) {
            return "error";
        }
        return "success";
    }


    /**
     * 退出
     * @param request
     * @return
     */
    @RequestMapping("/quit")
    public ModelAndView quit(HttpServletRequest request,HttpServletResponse response){

        request.getSession().removeAttribute(Constants.SESSION_USERNAME);

        Cookie cookie = new Cookie("userName", null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user",null);
        modelAndView.setViewName("index");
        return modelAndView;
    }

}
